package com.jp.knowledge.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.activity.ClassActivity;
import com.jp.knowledge.my.activity.DepartmentCreateActivity;
import com.jp.knowledge.my.activity.DepartmentRemaneActivity;
import com.jp.knowledge.my.activity.PositionActivity;
import com.jp.knowledge.my.activity.UserSettingDepartmentActivity;
import com.jp.knowledge.my.activity.UserSettingEditActivity;
import com.jp.knowledge.my.adapter.DepartmentAdapter;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.my.model.DepartmentModel;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.my.resources.OrganizeJoinRes;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.RecycleViewDiver;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jiayen     2017-03-30 14:25:06
 *
 * 部门管理fragment
 */
public class DepartmentManagerFragment extends BaseFragment implements RecycleVAdapter.OnItemClickListener, View.OnClickListener, ResultSubscriber.OnResultListener, RecycleVAdapter.OnItemLongClickListener {

    private UserData userData;
    private CommDialog deleteDialog;
    private int deletePosition;
    protected int requestCode;
    protected DepartmentAdapter adapter;

    @ViewInject(R.id.department_show_rv)
    private RecyclerView searchList;
    @ViewInject(R.id.department_btn_create)
    protected TextView departmentCreateBn;

    private View mView;
    private OrganizaModel company;
    /***准备加载*/
    private boolean isPred;
    /***数据加载完成*/
    private boolean   compeleteLoad;
    private List<DepartmentModel>  departmentModels;

    private String paramId;//参数id可能为公司 id也可能是班级id
    private boolean isUserEdit;
    public  DepartmentManagerFragment newInstance(OrganizaModel company,boolean isUserEdit){
        this.isUserEdit=isUserEdit;
        this.company=company;
        return  this;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_department_manager,null);
        x.view().inject(this, mView);
        init();
        isPred=true;
        onlazyLoad();
        return mView;
    }


    @Override
    protected void onlazyLoad() {
//        if(isVisible&&isPred&&!compeleteLoad){
                getData();
            isPred=false;
//        }
//
//        if(compeleteLoad){
//            isPred=false;
//        }
    }

    private void init() {

        userData = application.getUserData();
        if(userData==null){
            ToasUtil.toast(mContext,"登录信息有误,请重新登录!");
            getActivity().finish();
            return;
        }

        if(company==null){
            ToasUtil.toast(mContext,"公司信息为空");
            return;
        }else{
            int companyType = company.getCompanyType();
            if(companyType==2){
                paramId=company.getClassId();
            }else{
                paramId=company.getCompanyId();
            }

           int admin = company.getCompanyAdmin();
            if(admin==1&&!isUserEdit){//超级管理员
                departmentCreateBn.setVisibility(View.VISIBLE);
                departmentCreateBn.setOnClickListener(this);
            }else {
                departmentCreateBn.setVisibility(View.GONE);
            }
        }
        this.requestCode = getActivity().getIntent().getIntExtra(OrganizeJoinRes.REQUEST_CODE, 0);
//
        if(departmentModels==null)departmentModels= new ArrayList<DepartmentModel>();
        adapter = new DepartmentAdapter(mContext,departmentModels);
        adapter.addItemClickListener(this);
        searchList.setHasFixedSize(true);
        searchList.setLayoutManager(new LinearLayoutManager(mContext));
        searchList.addItemDecoration(new RecycleViewDiver(mContext, LinearLayout.HORIZONTAL));
        searchList.setAdapter(adapter);
//        getData();
        initDelDialog();
    }
    private void initDelDialog() {

        deleteDialog = new CommDialog(mContext);
        if(userData.getOrganizaType() == 2) {
            deleteDialog.setContent("是否删除该院系？");
        } else {
            deleteDialog.setContent("是否删除该部门？");
        }

        deletePosition = 0;
        deleteDialog.setLeft("取消");
        deleteDialog.setRight("删除");
        deleteDialog.setRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JsonObject param = new JsonObject();
                param.addProperty("token", HttpHelper.token);
                param.addProperty("id", paramId);
                param.addProperty("depaId", adapter.getData(deletePosition).getId());
                param.addProperty("type", company.getCompanyType());
                HttpHelper.getInstance(mContext)
                        .deleteDepartment(param, requestCode+1,DepartmentManagerFragment.this);
                deleteDialog.dismiss();
            }
        });
        adapter.addItemLongClickListener(this);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK || requestCode != this.requestCode || null == data)
            return;
        getData();
    }


    @Override
    public void onStart(int requestType) {
        loadingDialog.show();
    }
    @Override
    public void onCompleted(int requestType) {
        loadingDialog.cancel();
    }
    @Override
    public void onError(int requestType) {
        loadingDialog.cancel();
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext, data.getMessage());
        } else if(requestType == requestCode+1){
            adapter.removeData(deletePosition);
            ToasUtil.toast(mContext, "删除成功");
        } else if(requestType == this.requestCode){
            compeleteLoad=true;
            departmentModels = data.getList(DepartmentModel.class);
            adapter.updateAdapter(departmentModels);
        }
    }

    @Override
    public void itemSelect(int position) {
        Intent intent = getActivity().getIntent();
        if(isUserEdit){//人物编辑 则返回部门信息
            intent.putExtra(UserSettingDepartmentActivity.SELECTED_DEPARTMENT_NAME, adapter.getData(position).getName());
            intent.putExtra(UserSettingDepartmentActivity.SELECTED_DEPARTMENT_ID, adapter.getData(position).getId());
            getActivity().setResult(getActivity().RESULT_OK, intent);
           getActivity().finish();
        }else {
//            if(requestCode == OrganizeJoinRes.SCHOOL_INDEX)
//                intent.setClass(mContext, ClassActivity.class);
//            else
//                intent.setClass(mContext, PositionActivity.class);
//            startActivity(intent);

            startActivityForResult(new Intent(mContext, DepartmentRemaneActivity.class)
                    .putExtra("departmentName", adapter.getData(position).getName())
                    .putExtra("departmentId", adapter.getData(position).getId())
                    .putExtra("organizaId", company.getCompanyId())
                    .putExtra("type", company.getCompanyType()), requestCode);
        }

    }

    protected void getData(){
        JsonObject param = new JsonObject();
        param.addProperty("token", HttpHelper.token);
        param.addProperty("id",paramId);
        param.addProperty("type", company.getCompanyType());
        HttpHelper.getInstance(mContext).getDepartment(param, requestCode, this);
    }

    @Override
    public void onClick(View v) {
       if(v.getId() == R.id.department_btn_create){
            createBnClick();
        }
    }

    protected void createBnClick(){
        Intent intent = getActivity().getIntent();
        intent.setClass(mContext, DepartmentCreateActivity.class);
        intent.putExtra(OrganizeJoinRes.ID,paramId);
        intent.putExtra(OrganizeJoinRes.REQUEST_CODE, requestCode);
        if(requestCode == OrganizeJoinRes.SCHOOL_INDEX) {
            intent.putExtra(OrganizeJoinRes.TITLE_CREATE, "创建院系");
            intent.putExtra(OrganizeJoinRes.REMIND_CREATE, "编辑院系");
        } else{
            intent.putExtra(OrganizeJoinRes.TITLE_CREATE, getString(R.string.create_department_title));
            intent.putExtra(OrganizeJoinRes.REMIND_CREATE, getString(R.string.create_department_remind));
        }
        startActivityForResult(intent, requestCode);
    }

    @Override
    public boolean itemLongClick(int position) {
        if(isUserEdit)return  true;//信息编辑过来的 不支持 长按
        deletePosition = position;
        deleteDialog.show();
        return false;
    }

}
